const { set } = require("lodash")

/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/
const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'
class MyPromise {
    // 执行器
    constructor(executor) {
        try {
            executor(this.resolve,this.reject)
        } catch(e) {
            this.reject(e)
        }
    }

    // 成功的值
    value = undefined;
    // 失败的原因'
    reason = undefined
    // 当前的状态
    status = PENDING;
    // 存储成功的回调函数
    successCallback = []
    // 存储失败的回调函数
    failCallback = []
    resolve = value => {
        // 如果不是pending就返回
        if (this.status !== PENDING) return;
        this.value = value
        this.status = RESOLVED
        while (this.successCallback.length) this.successCallback.shift()();
    }
    reject = reason => {
        // 如果不是pending就返回
        if (this.status !== PENDING) return;
        this.reason = reason;
        this.status = REJECTED;
        while (this.failCallback.length) this.failCallback.shift()();
    }
    then = (fullfiedCallback,rejectedCallback) => {
        // 为了使then的参数更加灵活，例如可以传空，需要做一个判断
        fullfiedCallback ? fullfiedCallback : value => value;
        rejectedCallback ? rejectedCallback : reason => {throw reason};
        // 为了完成then的链式调用，所以需要返回一个MyPromise对象
        let promise2 = new MyPromise((resolve,reject) => { 
            // 状态resolve时调用成功的回调    
            if (this.status === RESOLVED) {
                setTimeout(() => {                    
                try {
                    // 异步操作，使得promise2可以传入resolvePromise
                        let x = fullfiedCallback(this.value)
                        // 需要判断x是普通值还是MyPromise对象
                        // 判断完了之后，如果是MyPromise对象就通过then取出值返回
                        resolvePromise(x,promise2,resolve,reject)
                    } catch(e) {
                        reject(e)
                    }
                }, 0);
            } else if(this.status === REJECTED) {
                // 状态reject时调用成功的回调 
                setTimeout(() => {
                try {
                        let x = rejectedCallback(this.reason)
                        resolvePromise(x,promise2,resolve,reject)
                    } catch(e) {
                        reject(e)
                    }
                }, 0);
            } else {
                // 存储成功的回调
                this.successCallback.push(() => {
                    setTimeout(() => {                    
                    try {
                            let x = fullfiedCallback(this.value)
                            resolvePromise(x,promise2,resolve,reject)
                        } catch(e) {
                            reject(e)
                        }
                    }, 0);
                })
                // 存储失败的回调
                this.failCallback.push(() => {
                    setTimeout(() => {
                    try {
                            let x = rejectedCallback(this.reason)
                            resolvePromise(x,promise2,resolve,reject)
                        } catch(e) {
                            reject(e)
                        }
                    }, 0);
                })
            }
        })
        return promise2;
    }

    // 捕获失败的原因
    catch = failCallback => {
        this.then(undefined,failCallback)
    }

    // 无论结果如何都要执行callback回调
    finally = callback => {
        callback.then(value => {
            return new MyPromise(callback()).then(() => value)
        },reason => {
            return new MyPromise(callback()).then(() => {throw reason})
        })
    }

    // 返回成功的回调
    static resolve = value => {
        if(value instanceof MyPromise) return value;
        return new Promise(resolve => {
            resolve(value)
        })
    }

    // 返回失败的回调
    static reject = reason => {
        if(reason instanceof MyPromise) return reason;
        return new Promise(_,reject => {
            reject(reason)
        })
    }

    // 迭代之后全部成功才能resolve
    static all = arr => {
        let res = []
        let len = arr.length;
        // 计数器，当数字等于arr的长度的时候代表着结束
        let index = 0;
        return new MyPromise((resolve,reject) => {
            addData = (key, value) => {
                res[key] = value;
                index++
                if(index = arr.length) resolve(res)
            }
            for(let i = 0; i < len; i++) {
                let current = arr[i]
                if(current instanceof MyPromise) {
                    current.then(value => {
                        addData(i,value)
                    }, reason => {
                        reject(reason)
                    })
                } else {
                    addData(i,current)
                }
           }
        })
    }

    static race = arr => {
        
    }
}

// 解析Promise
function resolvePromise(x,promise2,resolve,reject) {
    // 规避传入的x和promise2相同导致的引用循环
    if(x === promise2) return reject(new TypeError('err massge'));
    // 如果是MyPromise类型就通过then将值传递给promise对象
    if(x instanceof MyPromise) {
        x.then(resolve,reject)
    } else {
        // 普通值就通过resolve包裹
        resolve(x)
    }
}

module.exports = MyPromise;